

import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:trade/common/util/screen/screen_util.dart';
import 'package:trade/pages/trading_page/bean/period.dart';
import 'package:trade/theme/app_colors.dart';
import 'package:trade/widgets/dropdown_item_select.dart' as dropDown;

import '../model/trading_model.dart';

const _kIndicatorWidth = 20.0;
const _kIndicatorHeight = 2.0;
const _kMaxShowCount = 5;

///切换k线图时间粒度.如 1min, 5min, 15min, 30min, 60min, 4hour, 1day, 1mon, 1week, 1year
class PeriodBar extends StatefulWidget {
  final List<Period> periodList;
  final Function(Period)? onPeriodChange;

  const PeriodBar({
    Key? key,
    required this.periodList,
    this.onPeriodChange,
  })  : assert(periodList.length > 0),
        super(key: key);

  @override
  _PeriodBarState createState() => _PeriodBarState();
}

class _PeriodBarState extends State<PeriodBar> {
  int currentIndex = 0;
  GlobalKey _globalKey = GlobalKey();

  Period? selectValue;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var theme = Theme.of(context);
    final unselectedLabelStyle = TextStyle(
        fontSize: 12,
        fontWeight: FontWeight.w400,
        color: Colors.white,
        height: 14 / 12);
    final selectedLabelStyle = TextStyle(
        fontSize: 12,
        fontWeight: FontWeight.w500,
        color: appColors.blueAccent,
        height: 14 / 12);
    return DefaultTabController(
      length: widget.periodList.length,
      initialIndex: currentIndex,
      child: LayoutBuilder(
        key: _globalKey,
        builder: (c, box) {
          final indicatorWidth = box.maxWidth / min(_kMaxShowCount + 1, widget.periodList.length);
          final buttonCount = min(widget.periodList.length, _kMaxShowCount);
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  for (var i = 0; i < buttonCount; i++)
                    Flexible(
                      flex: 1,
                      child: InkWell(
                        onTap: (){
                          setState(() {
                            currentIndex = i;
                            selectValue = null;
                            widget.onPeriodChange?.call(widget.periodList[i]);
                          });
                        },
                        child: Container(
                          // color: Colors.red,
                          height: 24,
                          alignment: Alignment.center,
                          child: Text(
                            widget.periodList[i].title,
                            textAlign: TextAlign.center,
                            style: i == currentIndex
                                ? selectedLabelStyle
                                : unselectedLabelStyle,
                          ),
                        ),
                      ),
                    ),
                  if ((widget.periodList.length > _kMaxShowCount))
                    Flexible(
                      flex: 1,
                      child: dropDown.DropdownButton<Period>(
                        offset: 10,
                        child: Container(
                          width: indicatorWidth,
                          color: appColors.backgroundColor,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Container(
                                height: 24,
                                alignment: Alignment.center,
                                child: Text(
                                  selectValue?.title ?? '更多',
                                  textAlign: TextAlign.center,
                                  style: currentIndex >= _kMaxShowCount
                                      ? selectedLabelStyle
                                      : unselectedLabelStyle,
                                ),
                              ),
                              Container(
                                alignment: Alignment.bottomCenter,
                                height: 10,
                                margin: const EdgeInsets.only(left: 4),
                                child: Icon(
                                  Icons.perm_data_setting_rounded,
                                  color: (currentIndex >= 5
                                      ? selectedLabelStyle
                                      : unselectedLabelStyle)
                                      .color,
                                  size: 8,
                                ),
                              )
                            ],
                          ),
                        ),
                        iconSize: 0,
                        onChanged: (value) {
                          selectValue = value;
                          currentIndex = _kMaxShowCount;
                          setState(() {});
                          widget.onPeriodChange?.call(value);
                        },
                        itemSpacing: 12,
                        items: [
                          ...[
                            ...widget.periodList.sublist(_kMaxShowCount),
                          ].map((period) =>dropDown.DropdownMenuItem(
                            child: Container(
                              alignment: Alignment.center,
                              height: 24,
                              width: 64,
                              decoration: BoxDecoration(
                                color: appColors.backgroundColor,
                                borderRadius: BorderRadius.circular(5)
                              ),
                              child: Text(period.title,
                                  style: selectedLabelStyle),
                            ),
                            value: period,
                          ))
                        ],
                        style: currentIndex > _kMaxShowCount
                            ? selectedLabelStyle
                            : unselectedLabelStyle,
                      ),
                    ),
                ],
              ),
              const SizedBox(height: 6),
              _indicator(indicatorWidth, currentIndex),
            ],
          );
        },
      ),
    );
  }

  Widget _indicator(double indicatorWidth, int currentIndex) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 200),
      margin: EdgeInsets.only(
          left: indicatorWidth * currentIndex + (indicatorWidth - _kIndicatorWidth)/2),
      width: _kIndicatorWidth,
      height: _kIndicatorHeight,
      decoration: ShapeDecoration(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        color: appColors.blueAccent,
      ),
    );
  }
}
